package cn.xs.surveypark.struts2.action;

import javax.annotation.Resource;

import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.xs.surveypark.domain.User;
import cn.xs.surveypark.service.UserService;
import cn.xs.surveypark.util.DataUtil;
import cn.xs.surveypark.util.ValidateUtil;


@Controller
@Scope("prototype")
public class RegAction extends BaseAction<User> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -8786630060963417864L;
	
	private String confirmPassword;
	
	//注入userService
	@Resource
	private UserService userService;
	
	/**
	 * 到达注册页面
	 * @return
	 * 下面注解是跳过校验
	 */
	@SkipValidation
	public String toRegPage(){
		return "regPage";
	}
	
	/**
	 * 用户注册
	 * @return
	 */
	public String doReg(){
		model.setPassword(DataUtil.md5(model.getPassword()));
		userService.saveEntity(model);
		
		return SUCCESS;
	}

	@Override
	public void validate() {
		//1.非空校验
		if(!ValidateUtil.isValid(model.getEmail())){
			addFieldError("email", "email是必须填写!");
		}
		if(!ValidateUtil.isValid(model.getPassword())){
			addFieldError("password", "password是必须填写!");
		}
		if(!ValidateUtil.isValid(model.getNickName())){
			addFieldError("nickName", "nickName是必须填写!");
		}
		if(this.hasErrors()){
			return;
		}
		//2.密码一致行校验
		if(!model.getPassword().equals(confirmPassword)){
			addFieldError("password", "密码输入不一致！");
		}
		if(this.hasErrors()){
			return ;
		}
		
		//3.Email是否占用
		boolean b = userService.isRegisted(model.getEmail());
		if(b){
			addFieldError("email", "邮箱已占用！");
		}
	}

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}
	
	
}
